import calendar
import datetime

import numpy as np
import pandas as pd
from flask import Blueprint, current_app
from flask_cors import cross_origin
from flask import request

from app.Services.HealthServices.FoodServices.FoodCalServices import FoodCalServices
from app.Services.HealthServices.FoodServices.FoodCateServices import FoodCateServices
from app.Services.HealthServices.FoodServices.FoodRecordServices import FoodRecordServices
from app.Utils.Decorator.UserIdDecorator import inject_user_id
from app.Utils.Utils import success_response, error_response, return_response_

# 1. 创建蓝图对象
food_bp = Blueprint(
    name='food_bp',
    import_name=__name__,
    url_prefix='/health'
)

food_services = FoodRecordServices()
food_cate_services = FoodCateServices()
food_cal_services = FoodCalServices()


@food_bp.route('/food/get_detail_by_date', methods=['POST'])
@inject_user_id(default_user_id=1)  # 启用装饰器，默认值设为 1
def get_detail_by_date(user_id):
    """
    根据用户id|饮食摄入日期获取某日饮食摄入明细。
    """
    user_id = user_id
    food_id = request.cookies.get('food_id')


@food_bp.route('/food/get_food_cate_list', methods=['GET'])
def get_food_cate_list():
    """
    获取食物类型表。
    """
    status, res = food_cate_services.get_all_food_cates()
    return return_response_(status, res)


@food_bp.route('/food/get_food_name_by_cate_id', methods=['POST'])
def get_food_name_by_cate_id():
    """
    根据食物类别id查询对应的食物信息列表。
    """
    cate_id = request.json.get('cate_id', None)
    if not cate_id:
        return error_response(f"请提交对应的食物类别id后重试。")
    status, res = food_cal_services.get_food_cals_by_cate_id(cate_id)
    return return_response_(status, res)


# 新增饮食摄入记录
@food_bp.route('/food/add_intake_record', methods=['POST'])
@inject_user_id(default_user_id=1)  # 启用装饰器，默认值设为 1
def add_intake_record():
    """
    新增饮食摄入记录。
    """
    user_id = int(user_id)
    # 转成df
    record_df = pd.DataFrame(request.json)
    # 修改列名
    record_df.rename(columns={
        'gramWeight': 'act_intake_gram',
        'description': 'note',
        'id': 'food_id'
    }, inplace=True)
    # 计算实际摄入热量
    record_df['act_intake_kcal'] = record_df['act_intake_gram'] * record_df['caloriePer1g']
    # 去除中文名字，根据ID匹配。
    record_df.drop(columns=['caloriePer1g', 'name'], inplace=True)
    # 提交日期
    record_df['intake_date'] = datetime.date.today()
    # 提交时间
    record_df['submit_time'] = datetime.datetime.now().strftime('%H:%M:%S')
    for _, row in record_df.iterrows():
        _,food_cate_id = food_cate_services.get_food_cate_by_name(row['categoryLabel'])
        food_services.add_food_record(food_cate_id=food_cate_id['id'], user_id=user_id, food_id=row['food_id'],
                                      act_intake_gram=row['act_intake_gram'], intake_date=row['intake_date'], )
    return return_response_(True, f"新增{len(record_df)}条记录完成")


# 获取饮食摄入记录
@food_bp.route('/food/get_intake_record', methods=['POST'])
@inject_user_id(default_user_id=1)  # 启用装饰器，默认值设为 1
def get_intake_record(user_id):
    """
    获取饮食摄入记录
    """
    user_id = int(user_id)
    date_str = request.json.get('date_str', None)
    status, res = food_services.get_user_food_records(user_id=user_id, start_date=date_str, end_date=date_str,
                                                      operator_user_id=user_id)
    print(res)
    return return_response_(status, res)


# 获取所有可选的食物列表
@food_bp.route('/food/get_food_kcal_list', methods=['GET'])
def get_food_kcal_list():
    """
    获取所有可选的食物列表，格式与前端对应。
    """
    status, res = food_cal_services.get_all_food_cals()
    res = pd.DataFrame(res)
    grouped = res.groupby('food_cate_name').apply(
        lambda g: {
            'id': int(g['food_cate_id'].iloc[0]),  # 分类ID（假设同组ID一致）
            'label': g['food_cate_name'].iloc[0],  # 分类名称
            'foods': g.apply(
                lambda row: {
                    'id': row['id'],
                    'name': row['food_name'],
                    'caloriePer1g': float(np.round(row['kcal_per_piece'] / row['gram_per_piece'], 2)),  # 计算每1g热量
                    'type': '',  # 若需type可补充逻辑，此处留空
                    'description': ''  # 若需描述可补充逻辑，此处留空
                },
                axis=1
            ).to_list()
        }
    ).to_list()
    print(pd.DataFrame(grouped))
    return return_response_(status, grouped)
